from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from flow import create_vision_flow
import os

app = FastAPI()

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
async def read_root():
    return FileResponse("static/index.html")

@app.post("/api/extract-pdf")
async def extract_pdf(file: UploadFile = File(...)):
    # 保存上传的文件
    file_path = f"static/uploads/{file.filename}"
    
    with open(file_path, "wb") as f:
        f.write(await file.read())
    
    # 处理PDF
    flow = create_vision_flow()
    shared = {"pdf_path": file_path}
    flow.run(shared)
    
    # 返回结果
    if "results" in shared:
        return {
            "filename": file.filename,
            "text": shared["results"][0]["text"]
        }
    return {"error": "No text extracted"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)